<template>
  <div class="profile">
    <a-row :gutter="16">
      <!-- 个人信息卡片 -->
      <a-col :xs="24" :lg="8">
        <a-card title="个人信息" :bordered="false">
          <div class="profile-info">
            <div class="avatar-section">
              <a-avatar :size="80" :icon="h(UserOutlined)" />
              <h3>{{ userStore.userInfo?.nickName }}</h3>
              <a-tag :color="getRoleColor(userStore.userRole)">
                {{ getRoleText(userStore.userRole) }}
              </a-tag>
            </div>

            <a-descriptions :column="1" size="small">
              <a-descriptions-item label="账号">
                {{ userStore.userInfo?.accountName }}
              </a-descriptions-item>
              <a-descriptions-item label="邮箱">
                {{ userStore.userInfo?.email }}
              </a-descriptions-item>
              <a-descriptions-item label="手机号">
                {{ userStore.userInfo?.phoneNumber }}
              </a-descriptions-item>
              <a-descriptions-item
                v-if="userStore.isStudent && userStore.userInfo?.dormitoryName"
                label="宿舍地址"
              >
                {{ userStore.userInfo.dormitoryName }}
              </a-descriptions-item>
              <a-descriptions-item label="注册时间">
                {{ formatDate(userStore.userInfo?.createdAt) }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </a-card>
      </a-col>

      <!-- 编辑信息表单 -->
      <a-col :xs="24" :lg="16">
        <a-card title="编辑信息" :bordered="false">
          <a-form
            ref="formRef"
            :model="form"
            :rules="rules"
            layout="vertical"
            @finish="handleUpdate"
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="昵称" name="nickName">
                  <a-input
                    v-model:value="form.nickName"
                    placeholder="请输入昵称"
                  />
                </a-form-item>
              </a-col>

              <a-col :span="12">
                <a-form-item label="邮箱" name="email">
                  <a-input
                    v-model:value="form.email"
                    placeholder="请输入邮箱"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="手机号" name="phoneNumber">
                  <a-input
                    v-model:value="form.phoneNumber"
                    placeholder="请输入手机号"
                  />
                </a-form-item>
              </a-col>

              <a-col :span="12" v-if="userStore.isStudent">
                <a-form-item label="宿舍地址" name="dormitoryName">
                  <a-input
                    v-model:value="form.dormitoryName"
                    placeholder="请输入宿舍地址"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item>
              <a-space>
                <a-button
                  type="primary"
                  html-type="submit"
                  :loading="loading"
                >
                  <SaveOutlined />
                  保存修改
                </a-button>
                <a-button @click="handleReset">
                  <ReloadOutlined />
                  恢复原样
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { updateUser } from '@/api/user'
import { UserType } from '@/types'
import type { UserUpdateRequest } from '@/types'
import type { FormInstance } from 'ant-design-vue'
import type {Rule} from 'ant-design-vue/es/form'
import {
  UserOutlined,
  SaveOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'

const userStore = useUserStore()
const appStore = useAppStore()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive<UserUpdateRequest>({
  nickName: '',
  email: '',
  phoneNumber: '',
  dormitoryName: ''
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  dormitoryName: [
    { max: 100, message: '宿舍地址不能超过100个字符', trigger: 'blur' }
  ]
}

// 获取角色颜色
const getRoleColor = (role?: UserType) => {
  const colorMap = {
    [UserType.STUDENT]: 'blue',
    [UserType.REPAIR_WORKER]: 'green',
    [UserType.ADMIN]: 'red'
  }
  return role ? colorMap[role] : 'default'
}

// 获取角色文本
const getRoleText = (role?: UserType) => {
  const textMap = {
    [UserType.STUDENT]: '学生',
    [UserType.REPAIR_WORKER]: '维修工',
    [UserType.ADMIN]: '管理员'
  }
  return role ? textMap[role] : '未知'
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString()
}

// 初始化表单数据
const initForm = () => {
  if (userStore.userInfo) {
    form.nickName = userStore.userInfo.nickName
    form.email = userStore.userInfo.email
    form.phoneNumber = userStore.userInfo.phoneNumber
    form.dormitoryName = userStore.userInfo.dormitoryName || ''
  }
}

// 更新用户信息
const handleUpdate = async () => {
  try {
    loading.value = true
    const response = await updateUser(form)
    if (response.code === 0) {
      message.success('信息更新成功')
      // 重新获取用户信息
      await userStore.fetchUserInfo()
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  initForm()
}

onMounted(() => {
  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '个人中心' }
  ])

  initForm()
})
</script>

<style scoped>
.profile {
  padding: 0;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 24px;
}

.avatar-section h3 {
  margin: 16px 0 8px;
  font-size: 18px;
  font-weight: 600;
}

.ant-descriptions {
  text-align: left;
}
</style>
